package org.zffc.controller;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zffc.boot.starter.dto.MqttMessageDTO;
import org.zffc.boot.starter.service.MqttService;

import javax.annotation.Resource;
import java.util.stream.Stream;

/**
 * @Description:
 * @Note:
 * @Author: zhangfei
 * @Date: 2025/4/7 14:58
 **/
@RestController
@RequestMapping("/demo")
public class MqttController {
    @Resource
    private MqttService mqttService;

    @GetMapping(value = "/publish")
    public String createConnect(String topic,String message) {
        try {
            MqttMessageDTO messageDTO = new MqttMessageDTO();
            messageDTO.setPayload(message);
            messageDTO.setTopic(topic);
            mqttService.publish(messageDTO);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping(value = "/subscribe")
    public String subscribe(String topic) {
        try {
            mqttService.subscribe(topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping(value = "/unsubscribe")
    public String unsubscribe(String topic) {
        try {
            mqttService.unsubscribe((String[]) Stream.of(topic).toArray());
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return "ok";
    }
}
